<template>
  <div>
    <div v-if="loading" class="loading">
      <van-loading :color="rootThemeColor" type="spinner">{{ loadingText }}</van-loading>
    </div>
    <template v-if="error">
      <van-notice-bar left-icon="volume-o" wrapable :scrollable="false" @click="onErrorClick">
        {{ errorText }}
      </van-notice-bar>
    </template>
    <div v-if="success">
      <template v-if="enablePullRefresh">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <slot></slot>
        </van-pull-refresh>
      </template>
      <template v-else>
        <slot></slot>
      </template>
    </div>
  </div>
</template>

<script>
import {
  Loading as VanLoading,
  NoticeBar as VanNoticeBar,
  PullRefresh as VanPullRefresh
} from 'vant'
export default {
  name: 'PageLoading',
  inject: ['rootThemeColor'],
  components: {
    VanLoading,
    VanNoticeBar,
    VanPullRefresh
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    error: {
      type: Boolean,
      default: false
    },
    loadingText: {
      type: String,
      default: '加载中...'
    },
    errorText: {
      type: String,
      default: '请求失败，点击重新加载'
    },
    enablePullRefresh: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      refreshing: false
    }
  },
  computed: {
    success () {
      return !this.loading && !this.error
    }
  },
  methods: {
    onRefresh () {
      this.refreshing = false
      this.$emit('reload')
    },
    onErrorClick () {
      this.$emit('update:loading', true)
      this.$emit('update:error', false)
      this.$emit('reload')
    }
  }
}
</script>

<style lang="scss" scoped>
  .loading{
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
